const express = require('express');
const router = express.Router();
const User = require('../models/User');
const jwt = require('jsonwebtoken');
const auth = require('../middleware/auth');  // 直接导入auth
const JWT_SECRET = auth.JWT_SECRET;  // 从auth模块获取JWT_SECRET

// 调试中间件
router.use((req, res, next) => {
  console.log('Users route:', req.method, req.url);
  next();
});

router.post('/register', async (req, res) => {
  try {
    console.log('Register request:', req.body);
    const { username, password, phone, wechat } = req.body;
    
    const existingUser = await User.findOne({ username });
    if (existingUser) {
      return res.status(400).json({ error: '用户已存在' });
    }

    const user = new User({ username, password, phone, wechat });
    await user.save();

    const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: '7d' });
    console.log('Generated token:', token);
    
    res.json({ 
      token, 
      user: { 
        id: user._id, 
        username: user.username, 
        avatar: user.avatar,
        phone: user.phone,
        wechat: user.wechat
      } 
    });
  } catch (error) {
    console.error('Register error:', error);
    res.status(500).json({ error: '注册失败' });
  }
});

router.post('/login', async (req, res) => {
  try {
    console.log('Login request:', req.body);
    const { username, password } = req.body;
    
    const user = await User.findOne({ username });
    if (!user) {
      return res.status(400).json({ error: '用户不存在' });
    }

    const isPasswordValid = await user.comparePassword(password);
    if (!isPasswordValid) {
      return res.status(400).json({ error: '密码错误' });
    }

    const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: '7d' });
    console.log('Login generated token:', token);
    
    res.json({ 
      token, 
      user: { 
        id: user._id, 
        username: user.username, 
        avatar: user.avatar,
        phone: user.phone,
        wechat: user.wechat
      } 
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ error: '登录失败' });
  }
});

// 添加用户信息接口
router.get('/:id', async (req, res) => {
  try {
    const user = await User.findById(req.params.id).select('-password');
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: '获取用户信息失败' });
  }
});

module.exports = router;